//   MVCWin32Extras (Direct3DView.cpp)
//
//   Copyright 2010 Eric Llewellyn
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

#include "Direct3DView.h"

namespace MVCWin32Extras
{
	Direct3DView::Direct3DView()
	{
		g_pD3D = NULL;
		g_pd3dDevice = NULL;
	}

	Direct3DView::~Direct3DView()
	{
		if(g_pd3dDevice != NULL)
			g_pd3dDevice->Release();

		if(g_pD3D != NULL)
			g_pD3D->Release();
	}

	void Direct3DView::Init()
	{
		if( NULL == ( g_pD3D = Direct3DCreate9(D3D_SDK_VERSION) ) )
			return;

		D3DPRESENT_PARAMETERS d3dpp;
		ZeroMemory( &d3dpp, sizeof( d3dpp ) );
		d3dpp.Windowed = TRUE;
		d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
		d3dpp.EnableAutoDepthStencil = TRUE;
		d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
		d3dpp.BackBufferCount = 1;
		d3dpp.SwapEffect = D3DSWAPEFFECT_COPY;

		if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, GetHandle(),
			D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &g_pd3dDevice ) ) )
			return;

		g_pd3dDevice->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE);
		g_pd3dDevice->SetRenderState(D3DRS_ZENABLE,D3DZB_TRUE);
		::SetRect(&r,0,0,d3dpp.BackBufferWidth,d3dpp.BackBufferHeight);
	}

	void Direct3DView::PreDraw()
	{
		if( g_pd3dDevice == NULL )
			return;

		g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB( 0, 0, 0 ), 1.0f, 0);
	}

	void Direct3DView::Draw()
	{
	}

	void Direct3DView::PostDraw()
	{
		if( g_pd3dDevice == NULL )
			return;

		g_pd3dDevice->Present( &r, &r, NULL, NULL );
	}

	LPDIRECT3D9 Direct3DView::GetLpDirect3D9()
	{
		return g_pD3D;
	}

	LPDIRECT3DDEVICE9 Direct3DView::GetLpDirect3DDevice9()
	{
		return g_pd3dDevice;
	}
}
